import React from 'react';
import { Form, Select, Row, Col, Button, Tooltip, Icon, Input } from 'antd';
import PropTypes from 'prop-types';
import { countryDict } from '@/models/mineList';
import SalaryRefTable from '@/components/SalaryRefTable';
import classNames from 'classnames';
import { hideSalaryTable } from '@/utils/utils';
import styles from '../index.less';
import salary from './SalaryAdjust';
import { useSalaryincrecords, regularizationAdjust } from './utils';

const { Item } = Form;
const { Option } = Select;

// 当年初始薪资基数*上浮百分比+当前薪资
const getMoney = (type, per, base, month) => {
    if (type === '0') return Number(month).toFixed(0);
    if (!base) return '';
    // const result = month + base * window.parseInt(per) * 0.01 * (type === '1' ? 1 : -1)
    const result = month + base * window.parseFloat(per) * 0.01 * (type === '1' ? 1 : -1);
    return result.toFixed(0); // 转正原型要求四舍五入到个位， 测试也要求保留到个位
};

// HR确认申请
const HR = ({ form, type, detail }) => {
    const { getFieldDecorator } = form;
    const {
        currentSalary,
        companyId,
        salaryAdjTypeHr,
        salaryAdjPerHr,
        baseMonthSalary,
        employeeId,
        hrApproval,
        hrDelayDate,
        adjustSalary,
        monthSalary = 0
    } = detail;
    const findCompany = countryDict.find(company => company.id === companyId);
    const { unit } = findCompany || '';
    const {
        records: { incPer }
    } = useSalaryincrecords(employeeId);
    const getValue = () => {
        const hrType = form.getFieldValue('salaryAdjTypeHr');
        const hrPer = form.getFieldValue('salaryAdjPerHr');
        const defaultResult = currentSalary ? Number(currentSalary).toFixed(0) : '';
        const defaultYearResult = (16 * defaultResult).toFixed(0);
        if (!hrType || !hrPer || hrType === '0') return `${unit}${defaultResult}/月，即${unit}${defaultYearResult}/年`;
        const newResult = getMoney(hrType, hrPer, baseMonthSalary, monthSalary);
        const newYearResult = (16 * newResult).toFixed(0);
        // if (!hrType || !hrPer) return `${unit} ${detail.processState === 'success' ? monthSalary : result || ''}/月`;
        if (newResult) return `${unit}${newResult}/月，即${unit}${newYearResult}/年`;
        return `${unit}${defaultResult}/月，即${unit}${defaultYearResult}/年`;
    };
    const getSuggestLabel = () => {
        const regularType = regularizationAdjust.types.find(item => item.value === hrApproval);
        if (!regularType) return '';
        const isDelayed = regularizationAdjust.values.find(item => item.value === hrDelayDate);
        return `${regularType.name}${isDelayed ? `${isDelayed.label}` : ''}`;
    };
    const getAdjustLabel = () => {
        const adjustType = salary.types.find(item => item.value === salaryAdjTypeHr);
        if (!adjustType) return '';
        // 如果不变则不显示后面的内容
        if (adjustType.value === '0') return `${adjustType.name}`;
        return `${adjustType.name} ${salaryAdjPerHr ? `${salaryAdjPerHr}%` : ''} ${
            adjustSalary
                ? `${unit}${Number(adjustSalary).toFixed(0)}/月，即${unit}${Number(adjustSalary * 16).toFixed(0)}/年`
                : ''
        }`;
    };
    const punishmentOptions = [
        { label: '是', value: 1 },
        { label: '否', value: 0 }
    ];
    const mapValueToLabel = val => {
        const targetItem = punishmentOptions.find(item => item.value === val);
        if (!targetItem) return '';
        return targetItem.label;
    };
    const showSalary = () => {
        if (!currentSalary) return '';
        return `${unit}${Number(currentSalary).toFixed(0)}`;
    };
    const isConsistent = form.getFieldValue('salaryAdjTypeHr') === '0';
    return (
        <div>
            <div className={styles.title}>转正评估（HR）</div>
            <div className={classNames({ [styles.detailWrap]: type === 'detail' })}>
                <Item
                    required={type !== 'detail'}
                    label={
                        <span>
                            纪律处分&nbsp;
                            <Tooltip title="在试用期内是否有任何不当行为或纪律处分">
                                <Icon type="question-circle-o" />
                            </Tooltip>
                        </span>
                    }
                >
                    {type !== 'detail' &&
                        getFieldDecorator('punishment', {
                            rules: [
                                {
                                    required: true,
                                    message: '请选择纪律处分！'
                                }
                            ],
                            initialValue: detail.punishment
                        })(
                            <Select placeholder="请选择">
                                {punishmentOptions.map(item => (
                                    <Option key={item.value} value={item.value}>
                                        {item.label}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    {type === 'detail' &&
                        getFieldDecorator('punishment', [
                            {
                                initialValue: detail.punishment
                            }
                        ])(<span>{mapValueToLabel(detail.punishment)}</span>)}
                </Item>
                <Item
                    required={type !== 'detail'}
                    style={type !== 'detail' ? { marginBottom: 0 } : {}}
                    label={<span>转正建议</span>}
                >
                    {type !== 'detail' ? (
                        <Row gutter={8}>
                            <Col span={12}>
                                <Item>
                                    {getFieldDecorator('hrApproval', {
                                        initialValue: detail.hrApproval,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择转正建议！'
                                            }
                                        ]
                                    })(
                                        <Select
                                            onChange={() => {
                                                form.setFieldsValue({
                                                    hrDelayDate: undefined
                                                });
                                            }}
                                            placeholder="请选择"
                                        >
                                            {regularizationAdjust.types.map(item => (
                                                <Option
                                                    // disabled={item.value === '1' && incPer === 50}
                                                    key={item.value}
                                                    value={item.value}
                                                >
                                                    {item.name}
                                                </Option>
                                            ))}
                                        </Select>
                                    )}
                                </Item>
                            </Col>
                            <Col span={12}>
                                <Item>
                                    {getFieldDecorator('hrDelayDate', {
                                        initialValue: detail.hrDelayDate,
                                        rules: [
                                            {
                                                validator(_, value, callback) {
                                                    if (form.getFieldValue('hrApproval') !== 0) {
                                                        if (!value) {
                                                            callback('请选择延期时长！');
                                                        } else {
                                                            callback();
                                                        }
                                                    } else {
                                                        callback();
                                                    }
                                                }
                                            }
                                        ]
                                    })(
                                        <Select
                                            allowClear
                                            disabled={form.getFieldValue('hrApproval') === 0}
                                            placeholder={form.getFieldValue('hrApproval') !== 0 && '请选择'}
                                        >
                                            {regularizationAdjust.values.map(item => (
                                                <Option key={item.value} value={item.value}>
                                                    {item.label}
                                                </Option>
                                            ))}
                                        </Select>
                                    )}
                                </Item>
                            </Col>
                        </Row>
                    ) : (
                        getSuggestLabel()
                    )}
                </Item>
                <Item label="当前薪资" style={currentSalary ? {} : { display: 'none' }}>
                    {getFieldDecorator('currentSalary', [
                        {
                            initialValue: currentSalary
                        }
                    ])(<span>{showSalary()}</span>)}
                </Item>
                <Item
                    required={type !== 'detail'}
                    style={type !== 'detail' ? { marginBottom: 0 } : {}}
                    label="调整后薪资"
                >
                    {type !== 'detail' ? (
                        <Row type="flex" gutter={8}>
                            <Col className={styles.flex}>
                                <Item>
                                    {getFieldDecorator('salaryAdjTypeHr', {
                                        initialValue: detail.salaryAdjTypeHr,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择薪资变化类型！'
                                            }
                                        ]
                                    })(
                                        <Select
                                            onChange={() => {
                                                form.setFields({
                                                    salaryAdjPerHr: {
                                                        value: undefined
                                                    }
                                                });
                                            }}
                                            placeholder="请选择"
                                        >
                                            {salary.types.map(item => (
                                                <Option
                                                    disabled={item.value === '1' && incPer === 50}
                                                    key={item.value}
                                                    value={item.value}
                                                >
                                                    {item.name}
                                                </Option>
                                            ))}
                                        </Select>
                                    )}
                                </Item>
                            </Col>
                            <Col className={styles.flex}>
                                <Item>
                                    {getFieldDecorator('salaryAdjPerHr', {
                                        initialValue: detail.salaryAdjPerHr,
                                        rules: [
                                            {
                                                validator(_, value, callback) {
                                                    if (form.getFieldValue('salaryAdjTypeHr') !== '0') {
                                                        if (
                                                            !value ||
                                                            value > 50 ||
                                                            value < 1 ||
                                                            !/^[0-9]+([.]{1}[0-9]+){0,1}$/.test(value)
                                                        ) {
                                                            return callback('输入1-50任意数');
                                                        }
                                                        return callback();
                                                    }
                                                    return callback();
                                                }
                                            }
                                        ]
                                    })(
                                        // <Select
                                        //     disabled={form.getFieldValue('salaryAdjTypeHr') === '0'}
                                        //     allowClear
                                        //     placeholder={form.getFieldValue('salaryAdjTypeHr') !== '0' && '请选择'}
                                        // >
                                        //     {salary
                                        //         .getValues(form.getFieldValue('salaryAdjTypeHr') === '1' ? incPer : 0)
                                        //         .map(item => (
                                        //             <Option key={item} value={item}>
                                        //                 {item}%
                                        //             </Option>
                                        //         ))}
                                        // </Select>
                                        <Input
                                            suffix={isConsistent ? '' : '%'}
                                            disabled={isConsistent}
                                            placeholder={
                                                form.getFieldValue('salaryAdjTypeHr') !== '0' && '输入1-50任意数'
                                            }
                                        ></Input>
                                    )}
                                </Item>
                            </Col>
                            {baseMonthSalary && (
                                <Col>
                                    <Button disabled>{getValue()}</Button>
                                </Col>
                            )}
                        </Row>
                    ) : (
                        getAdjustLabel()
                    )}
                </Item>
                {!hideSalaryTable && (
                    <Item label="薪资参考" wrapperCol={{ sm: { span: 20 }, md: { span: 20 } }}>
                        <SalaryRefTable postId={detail.postId} companyId={detail.companyId} />
                    </Item>
                )}
            </div>
        </div>
    );
};

HR.propTypes = {
    type: PropTypes.oneOf(['edit', 'detail']).isRequired
};

export default HR;
